
package icu.d4peng.basic.knife4j.util;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;

import com.github.xiaoymin.knife4j.core.extend.OpenApiExtendMarkdownChildren;
import com.github.xiaoymin.knife4j.core.util.CommonUtils;

/**
 * @author d4peng d4peng@qq.com
 * @date 2023-11-25 19:42:44
 */
public class MarkdownUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(MarkdownUtils.class);

	/**
	 * Resolve markdown files
	 *
	 */
	public static OpenApiExtendMarkdownChildren resolveMarkdownResource(Resource resource) {
		try {
			if (resource != null) {
				OpenApiExtendMarkdownChildren markdownFile = new OpenApiExtendMarkdownChildren();
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("read file:" + resource.getFilename());
				}
				// 只读取md
				if (Objects.toString(resource.getFilename(), "").toLowerCase().endsWith(".md")) {
					// if (".md".equals(Objects.toString(resource.getFilename(),""))){
					try {
						String title = CommonUtils.resolveMarkdownTitle(resource.getInputStream(),
								resource.getFilename());
						markdownFile.setTitle(title);
						markdownFile.setContent(
								new String(CommonUtils.readBytes(resource.getInputStream()), StandardCharsets.UTF_8));
						return markdownFile;
					}
					catch (Exception e) {
						LOGGER.warn("(Ignores) Failed to read Markdown files,Error Message:{} ", e.getMessage());
					}
				}
			}
		}
		catch (Exception e) {
			LOGGER.warn("(Ignores) Failed to read Markdown files,Error Message:{} ", e.getMessage());
		}
		return null;
	}

}
